#!/usr/bin/python
# -*- coding: utf-8 -*-
############################################################################
#
# visor.py
# Client per a connectarse al lector de dades i visualitzar les lectures
# i gràfiques.
#
# Author.......: Tomeu Capó Capó 2010 (C)
# Last Modified: 29/01/2010
# Use under terms of GNU public licence.

import time, sys, os
from PyQt4 import QtCore, QtGui

# Moduls especifics de l'aplicació

from clientThread import *
from grafiques import *
from visorVariable import *
from configuracio import *

# Moduls de la GUI

from ui.frmPrincipal import Ui_finestraPrincipal

################################################################################
# Visor GUI

class Visor(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.visors = {}
        self.grafiques = {}

        self.col = 1
        self.fila = 1
        self.lineTable = 1

        self.cliThr = None

        self.ui = Ui_finestraPrincipal()
        self.ui.setupUi(self)

        self.dConfig = Configuracio()

        self.connect(self.ui.actionConnectar, SIGNAL("triggered()"), self.onCmdConnectar)
        self.connect(self.ui.actionDesconnectar, SIGNAL("triggered()"), self.onCmdDesconnectar)
        self.connect(self.ui.actionIniciar, SIGNAL("triggered()"), self.onCmdIniciar)

        self.connect(self.ui.actionExportaGrafiques, SIGNAL("triggered()"), self.onCmdExportarGrafiques)
        self.connect(self.ui.actionSobre_el_programa, SIGNAL("triggered()"), self.onCmdAbout)
        self.connect(self.ui.actionConfiguracio, SIGNAL("triggered()"), self.onCmdConfiguracio)

        #self.connect(self.ui.action, SIGNAL("triggered()"), self.onCmdIniciar)
        #self.connect(self.ui.actionAturar, QtCore.SIGNAL("triggered()"), self.onCmdAturar) 
 
        self.ui.actionIniciar.setEnabled(0)
        self.ui.actionDesconnectar.setEnabled(0)

        self.ipServer = str(self.dConfig.settings.value("ipServidor").toString())
        self.portServer = int(self.dConfig.settings.value("portServidor").toString())
        self.dirExport = str(self.dConfig.settings.value("dirExport").toString())
 
    def defColsHist(self):
        if len(self.cliThr.vars)<1:
           return
                 
        titolsTaula = []
        for var in self.cliThr.vars:
            for i in range(len(self.cliThr.vars[var])):
                titolsTaula.append("%(t)s %(ind)d" % {"t": self.cliThr.defs[var][2], "ind":i})

        self.ui.tableWidget.setColumnCount(len(titolsTaula))
        self.ui.tableWidget.setHorizontalHeaderLabels(titolsTaula)
        self.lineTable=0
 
    def pintaVars(self):

        # Refresca els displays actius

        for varName, visor in self.visors.iteritems():
            visor.actualitza(self.cliThr.vars[varName])

        # Refresca grafiques

        for varName, grafica in self.grafiques.iteritems():
            grafica.afegirValor(self.cliThr.vars[varName])

        # Afegeix valor a la taula de historial

        if len(self.cliThr.vars)>0:
           col=0
           self.ui.tableWidget.setRowCount(self.lineTable+1)

           for varName, values in self.cliThr.vars.iteritems():
               for val in values:
                   self.ui.tableWidget.setItem(self.lineTable, col, QtGui.QTableWidgetItem(QString(str(val))))
                   col+=1

           self.lineTable+=1

    def onCmdConfiguracio(self):
        self.dConfig.cliThr = self.cliThr
        self.dConfig.carregar()

        if self.dConfig.exec_():
           self.dConfig.guardar()
           self.ipServidor=str(self.dConfig.settings.value("ipServidor").toString())

    def onCmdAbout(self):
        QtGui.QMessageBox.about(self,self.tr("Sobre el programa"), u"Visor 1.0\n\nClient per poder monitoritzar el servidor de lectures.\nTomeu Capó i Capó 2009 (C)")

    def onCmdExportarGrafiques(self):
        for varName, finGraf in self.grafiques.iteritems():
            nomFitxer = "%s_%s%s%s.pdf" % (varName, time.localtime()[0], time.localtime()[1], time.localtime()[2])
            finGraf.grafica.guarda(os.path.join(self.dirExport, nomFitxer))
            
        QtGui.QMessageBox.information(self,self.tr("Info"),"Exportades grafiques a fitxers PDF a %s" % self.dirExport)
 

    def onCmdConnectar(self):
        try:
          self.cliThr = clientThread(self.ui, (self.ipServer,self.portServer))
          self.connect(self.cliThr, SIGNAL("pintaVars()"), self.pintaVars) 
          self.connect(self.cliThr, SIGNAL("defColsHist()"), self.defColsHist)
          self.cliThr.connectar()
        except Exception, err:
          QtGui.QMessageBox.critical(self,self.tr("Error"),str(err))
        else:
          self.ui.actionConnectar.setEnabled(0)
          self.ui.actionDesconnectar.setEnabled(1)

          items = []
          self.dConfig.cliThr = self.cliThr

          descs = self.cliThr.defs

          for p in self.cliThr.conf[2]:
              item = QtGui.QTreeWidgetItem([p, (descs[p][2] if p in descs.keys() else "")])
              item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) 
              item.setCheckState(2, Qt.Unchecked) 
              item.setCheckState(3, Qt.Unchecked)
              items.append(item)

          arrel = QtGui.QTreeWidgetItem([self.cliThr.id.rstrip(), ""])
          arrel.addChildren(items)
          self.ui.arbreAnalitzadors.insertTopLevelItem(0, arrel)
          self.ui.arbreAnalitzadors.expandItem(arrel)

          self.connect(self.ui.arbreAnalitzadors, SIGNAL("itemChanged(QTreeWidgetItem *, int)"), self.onSeleccioVariable)
          self.cliThr.start()

    def onCmdDesconnectar(self):
        if self.cliThr.isRunning():
           self.ui.statusbar.showMessage("Desconnectant ...", 1) 
           self.cliThr.seguir = False
           self.cliThr.terminate()
           self.ui.actionConnectar.setEnabled(1)
           self.ui.actionDesconnectar.setEnabled(0)
           self.buidaTot()

           del self.cliThr
           self.cliThr = None

    def onCmdIniciar(self):
        self.ui.actionIniciar.setEnabled(0)
        self.cliThr.iniciar()
           
    def onSeleccioVariable(self, widgetItem, colum):
        if len(self.cliThr.vars)<1:
           return

        nomVar = str(widgetItem.text(0))
        descVar = widgetItem.text(1)

        if colum == 2:
           if widgetItem.checkState(colum) == Qt.Checked:
              visorNou = visorVariable(descVar, QtGui.QBoxLayout.TopToBottom, self.cliThr.vars[nomVar])        
              self.visors[nomVar] = visorNou
              self.ui.gridVisors.addWidget(visorNou, self.fila, self.col)         

              self.col = self.col + 1
   
              if self.col > 3:
                 self.col = 1 
                 self.fila = self.fila+1
           else:
              if widgetItem.checkState(colum) == Qt.Unchecked:
                 self.ui.gridVisors.removeWidget(self.visors[nomVar])
                 del self.visors[nomVar]
                 self.repintaVisors()
        else:
           if widgetItem.checkState(colum) == Qt.Checked:
              graficaNova = finestraGrafica(3)
              graficaNova.setTitols("Hora", descVar)
              graficaNova.setAttribute(Qt.WA_DeleteOnClose | Qt.WA_LayoutOnEntireRect)
              graficaNova.setWindowFlags(Qt.SubWindow)
              graficaNova.setWindowTitle(descVar)
              graficaNova.resize(720,390)
              graficaNova.setMaximumSize(720,390)

              self.grafiques[nomVar] = graficaNova
              self.ui.zonaGrafiques.addSubWindow(graficaNova)
              graficaNova.show()
           else:
              if widgetItem.checkState(colum) == Qt.Unchecked:
                 self.ui.zonaGrafiques.removeSubWindow(self.grafiques[nomVar])
                 del self.grafiques[nomVar] 
          
    def buidaTot(self):
        self.col = 1
        self.fila = 1
        for varName, visor  in self.visors.iteritems():
            self.ui.gridVisors.removeWidget(visor)
            del visor

        for varName, finGraf in self.grafiques.iteritems():
            self.ui.zonaGrafiques.removeSubWindow(finGraf)
            del finGraf 
 
        self.ui.arbreAnalitzadors.clear()

    def repintaVisors(self):
        self.col = 1
        self.fila = 1    
        for varName, visor in self.visors.iteritems():
            self.ui.gridVisors.addWidget(visor, self.fila, self.col)
            
            self.col = self.col + 1
   
            if self.col > 3:
               self.col = 1 
               self.fila = self.fila+1


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    v = Visor()
    v.show()
    sys.exit(app.exec_())
